//
//  GKNovelTableController.swift
//  MySwiftObject
//
//  Created by wangws1990 on 2020/9/8.
//  Copyright © 2020 wangws1990. All rights reserved.
//

import UIKit
@objc protocol GKNovelTableDelegate :NSObjectProtocol {
    @objc optional func controller(ctrl : GKNovelTableController)
}
class GKNovelTableController: BaseTableViewController {
    
    convenience init(delegate :GKNovelTableDelegate) {
        self.init()
        self.delegate = delegate
    }
    public var chapter     :NSInteger = 0
    public var chapterInfo :GKNovelChapterInfo? = nil
    public var content     :GKNovelContent?{
        get{
            return self.novelContent
        }
    }
    public func setData(){
        self.listData.removeAll()
        self.mainView.image = GKNovelSetManager.defaultSkin()
        self.refreshData(page: 0)
    }
    
    private weak var delegate :GKNovelTableDelegate? = nil
    private var novelContent :GKNovelContent? = nil
    private lazy var listData : [GKNovelContent] = {
        return []
    }()
    private lazy var mainView: UIImageView = {
        let mainView : UIImageView = UIImageView()
        mainView.isUserInteractionEnabled = false
        return mainView;
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        if #available(iOS 11.0, *) {
            self.tableView.contentInsetAdjustmentBehavior = .never
        } else {
            // Fallback on earlier versions
        }
        self.view.addSubview(self.mainView)
        self.mainView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        self.view.sendSubviewToBack(self.mainView)
        self.setupEmpty(scrollView: self.tableView)
        self.setupRefresh(scrollView: self.tableView, options: .defaults)
        self.view.backgroundColor = UIColor.clear
        self.tableView.backgroundColor = UIColor.clear
        self.tableView.contentInset = UIEdgeInsets.init(top:STATUS_BAR_HIGHT, left: 0, bottom: 0, right: 0)
        self.setData()
    }
    override func refreshData(page: Int) {
        if self.chapterInfo != nil {
            if(page == 1){
                self.chapter = self.chapter == 0 ? self.chapter : self.chapter - 1
            }else if(page > 1){
                self.chapter = (self.chapterInfo?.chapters.count)! > self.chapter + 1 ? self.chapter + 1 : self.chapter
            }
            let info :GKNovelChapter = self.chapterInfo!.chapters[self.chapter]
            GKNovelNet.bookContentModel(bookId:self.chapterInfo!._id, model: info, sucesss: { (content) in
                DispatchQueue.global().async {
                        content.pageContent()
                    DispatchQueue.main.async {
                        self.novelContent = content
                        if self.haveFirstData(info: info){
                            self.tableView.reloadData()
                            self.endRefresh(more: true)
                            return
                        }
                        else if self.haveLastData(info: info){
                            self.tableView.reloadData()
                            self.endRefresh(more: false)
                            return
                        }
                        if(page == 1){
                            self.listData.insert(content, at: 0)
                        }else{
                            self.listData.append(content)
                        }
                        if let delegate = self.delegate{
                            delegate.controller?(ctrl: self)
                        }
                        self.tableView.reloadData()
                        self.endRefresh(more:(self.chapterInfo?.chapters.count)! > self.chapter)
                    }
                }
            }) { (error) in
                self.endRefreshFailure()
            }
        }
    }
    private func haveFirstData(info :GKNovelChapter)-> Bool{
        if self.listData.count == 0 {
            return false
        }
        let content = self.listData.first
        let first = self.chapterInfo?.chapters.first
        return content?.chapterId == first?.chapterId && info.chapterId == content?.chapterId
    }
    private func haveLastData(info :GKNovelChapter)-> Bool{
        if self.listData.count == 0 {
            return false
        }
        let content = self.listData.last
        let last = self.chapterInfo?.chapters.last
        return content?.chapterId == last?.chapterId && info.chapterId == content?.chapterId
    }
    override func numberOfSections(in tableView: UITableView) -> Int {
        return self.listData.count
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let content = self.listData[section]
        return content.pageCount
    }
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.00001
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let content = self.listData[indexPath.section]
        let cell = GKNovelTableViewCell.cellForTableView(tableView: tableView, indexPath: indexPath)
        cell.content = content.attContent(page: indexPath.row);
        return cell
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let height = scrollView.frame.size.height
        let contentYoffset = scrollView.contentOffset.y
        let bottom = scrollView.contentSize.height - contentYoffset
        if bottom < height{
            
        }else{
            
        }
    }
}
